<template>
  <div class="bg-white w-full h-full">
    <div class="min-w-[260px] h-full flex flex-col px-3">
      <div class="mb-3">
        <div class="text-[#6F6F6F] text-[14px] mb-2">
          1.选择团队成员
          <AButton
            class="text-[14px]"
            shape="circle"
            :icon="h(ReloadOutlined)"
            :loading="getListLoading"
            @click="() => getDataList()"
          />
        </div>
        <Flex class="max-h-36 overflow-y-auto" wrap="wrap" gap="10">
          <template v-for="member in data" :key="member.id">
            <div
              class="relative min-w-20 max-w-28 w-[30%] h-10 flex flex-col text-center justify-center border border-[#00A0E9] rounded-md cursor-pointer"
              :class="[member.checked ? 'bg-[#00A0E9] text-[#ffffff]' : 'text-[#999999]']"
              @click="() => (member.checked = !member.checked)"
            >
              <CheckCircleFilled v-if="member.checked" class="absolute top-1 right-1" />
              <div class="text-[12px] truncate px-1">{{ member.realname }}</div>
              <div class="text-[10px] truncate">{{ member.mobile }}</div>
            </div>
          </template>
        </Flex>
      </div>
      <div class="mb-3">
        <div class="text-[#6F6F6F] text-[14px] mb-2">2.选择发送时间</div>
        <DatePicker
          class="w-full rounded-none"
          placement="bottomRight"
          v-model:value="sendDate"
          :placeholder="useSendDatePicker ? '请选择发送时间' : '请选择发送时间(仅选中成员可用)'"
          :disabled="!useSendDatePicker"
          :disabled-date="disabledDate"
        />
      </div>
      <div class="mb-3 flex-1 relative">
        <div class="text-[#6F6F6F] text-[14px] mb-2">3.今日选品派发</div>
        <Textarea
          class="rounded-none text-[12px] text-[#999999] resize-none !h-[calc(100%-100px)]"
          v-model:value="products"
          :rows="15"
        />
        <div class="text-[#FF0000] text-[10px] text-right mt-1">
          严格遵循:产品标题 ID 产品链接 销量 到手佣金 产品
        </div>
        <div class="absolute left-3 right-3 bottom-1 flex justify-center items-center p-1">
          <AButton
            class="bg-[#001428] text-[#FFFFFF] text-[15px] w-full max-w-96"
            type="primary"
            :loading="sendLoading"
            :disabled="!useSendTaskBtn"
            @click.stop="handleSendTask"
          >
            <template #icon
              ><img
                :src="PaperPlane"
                class="inline-block w-[18px] h-[15px] mt-[-2px] mr-1" /></template
            >发送任务</AButton
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import type { TeamMemberBase, CheckTaskReq } from '@main/service/team/type';
import { getTeamMemberApi, checkTaskApi, sendTaskApi } from '@main/service/team';
import { useUserStore } from '@/shared/store/user';
import { useMessage } from '@shared/hooks/web/useMessage';
import dayjs, { Dayjs } from 'dayjs';
import { Flex, Textarea, DatePicker, message } from 'ant-design-vue';
import { ref, onMounted, computed, h } from 'vue';
import { CheckCircleFilled, ReloadOutlined } from '@ant-design/icons-vue';
import PaperPlane from '@main/assets/images/paperplane.webp';

interface DataItem extends TeamMemberBase {
  checked?: boolean;
}

const userStore = useUserStore();
const { notification } = useMessage();

const data = ref<DataItem[]>([]);
const sendDate = ref<Dayjs>();
const products = ref('');
const useSendDatePicker = computed(() => {
  const hasChecked = data.value.some((x) => x.checked);
  if (!hasChecked) sendDate.value = undefined;
  return hasChecked;
});
const useSendTaskBtn = computed(
  () => useSendDatePicker.value && sendDate.value && products.value.trim() !== ''
);
const getListLoading = ref(false);
const sendLoading = ref(false);

const handleSendTask = async () => {
  sendLoading.value = true;

  const state = await handleCheckTask();
  if (state) {
    sendLoading.value = false;
    return;
  }

  const res = await sendTaskApi({
    sending_time: sendDate.value!.format('YYYY-MM-DD'),
    members: data.value
      .filter((x) => x.checked)
      .map((x) => x.id)
      .join(','),
    products: products.value
  });
  sendLoading.value = false;
  if (res) {
    message.success('发送任务成功');
    window.clientAppSdk.ipc.ipcRenderer.send('rc:router-page-data-change', ['TeamToday']);
  } else message.error('发送任务失败');
};

const handleCheckTask = async () => {
  if (!useSendDatePicker.value || !sendDate.value) return;
  const params: CheckTaskReq = {
    sending_time: sendDate.value.format('YYYY-MM-DD'),
    members: data.value
      .filter((x) => x.checked)
      .map((x) => x.id)
      .join(',')
  };
  //已经发送过的禁止发送
  const membersTasks = await checkTaskApi(params);
  return membersTasks.some((memberTasks) =>
    memberTasks.itemIds.some((taskId) => {
      const existingTask = products.value.indexOf(taskId) > -1;
      if (existingTask)
        notification.open({
          message: '已有任务检测',
          description: `成员${memberTasks.member_realname}任务${taskId}已存在`,
          duration: null,
          placement: 'topRight'
        });
      return existingTask;
    })
  );
};

const getDataList = async () => {
  if (getListLoading.value) return;
  getListLoading.value = true;
  const { is_leader, members } = await getTeamMemberApi();
  data.value = members;
  getListLoading.value = false;
  if (!is_leader) {
    userStore.logoutAction();
  }
};

onMounted(async () => {
  await getDataList();
});

const disabledDate = (current: Dayjs) => {
  return current && (current < dayjs().add(-1, 'day') || current > dayjs().add(1, 'day'));
};
</script>
